import { Button, Collapse, Icon, Radio,Tag } from "antd";
import { formatMessage } from 'umi-plugin-react/locale';
import React from "react";
import ReferAnswerShow from "./referAnswerShow";
import UpdateAnswerModal from "./updateAnswerModal";
import UserSession from "@/UserSession";
import styles from "./answerStyle.less"
import { connect } from "dva";
import { doRobotList } from "@/services/robotManagement";
import { fetchDetailCustomBySlotId } from "@/services/basiccapacity";

class MoreAnswers extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      answerSwitch:0,
      answerList:[]
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  //个性化答案开关
  onChangeAnswerSwitch = e => {
    this.setState({
      answerSwitch:e.target.value
    })
  }

  //打开添加编辑答案弹窗
  openModal = (type) => {
    this.UpdateAnswerModal.openModal(type)
  }

  //添加编辑答案弹窗点击确定
  answerSubmit = (answerResult,type,answerIndex) => {
    const { answerList } = this.state;
    if(type === 'add'){
      answerList.push(answerResult)
    }
    if(type === 'edit'){
      answerList[answerIndex] = answerResult
    }
    this.setState({
      answerList
    })

    console.log(answerList);
  }

  //处理详情获得的数据
  setAnswersFromDetail = async answerList => {
    if(!answerList){
      return false;
    }
    const { slotData } = this.props;
    const robotRes = await doRobotList({current:1,size:999999})
    let slotRes = []
    if(slotData && slotData.length > 0){
      const ids = slotData.map(item => item.id);
      slotRes = await fetchDetailCustomBySlotId({ids})
    }
    for(let item of answerList){
      //返回的数据中 用户标签为空数组 则处理为全部标签
      if(item.userTagIdList == null || item.userTagIdList.length === 0){
        item.userTagIdList = [{id:'all',tagName:formatMessage({ id: 'moreAnswers.label.allTags' })}]
      }
      //返回的数据中 应用为空数组 则处理为全部应用
      if(item.robotList == null || item.robotList.length === 0){
        item.robotList = [{robotId:'all',robotName:formatMessage({ id: 'moreAnswers.label.allApplications' })}]
      }
      // //返回的数据中 应用的个数与应用列表的个数相等 则处理为全部应用
      // if(item.robotList == null || item.robotList.length === robotRes.length){
      //   item.robotList = [{robotId:'all',robotName:'全部应用'}]
      // }
      //返回的数据中 若有词槽 且词槽的词槽值为空 则处理为全部词槽
      //返回的数据中 若有词槽 且词槽的词槽值与该词槽的核心词个数相等 则处理为全部词槽
      if(item.slotValues && item.slotValues.length > 0){
        for(let slot of item.slotValues){
          const detailIndex = slotRes.findIndex(d => d.id === slot.id)
          const detailWords = detailIndex != -1 ? slotRes[detailIndex].items.map(s => s.word) : []
          if(slot.values.length === 0){
            slot.values = [formatMessage({ id: 'moreAnswers.label.allSlots' })]
          }
          // if(slot.values.length === detailWords.length){
          //   slot.values = ['全部词槽']
          // }
        }
      }
      item.contentType = item.contentType + ''
    }
    console.log(answerList);
    this.setState({
      answerList,
      answerSwitch:answerList.length > 0 ? 1 : 0
    })
  }

  //处理提交数据
  dealtWithAnswers = () => {
    const { answerList,answerSwitch } = this.state;
    const { dispatch,slotData } = this.props
    
    for(let item of answerList){
      const userIds = item.userTagIdList.map(user => user.id)
      const appIds = item.robotList.map(robot => robot.robotId)
      if(userIds.indexOf('all') != -1){
        item.userTagIdList = []
      }
      if(appIds.indexOf('all') != -1){
        item.robotList = []
      }
      //处理词槽中的全部词槽
      if(item.slotValues && item.slotValues.length > 0){
        for(let slot of item.slotValues){
          //若词槽值为全部词槽 则修改为全部的词槽值
          if(slot.values.indexOf('全部词槽') != -1){
            slot.values = []
          }
        }
      }
      item.contentType = parseInt(item.contentType)
    }
    return answerSwitch == 1 || (slotData && slotData.length > 0) ? answerList : []
  }

  //编辑答案
  editAnswer = (e,item,index) => {
    e.stopPropagation();
    this.UpdateAnswerModal.openModal('edit',item,index)
  }

  //删除答案
  removeAnswer = (e,item,index) => {
    e.stopPropagation();
    const { answerList } = this.state;
    let newAnswers = answerList.filter((item, i) => i != index);
    this.setState({
      answerList:newAnswers
    })
  }

  //词槽全部删除，则去掉所有词槽答案的词槽
  removeSlotForAllAnswer = () => {
    const { answerList } = this.state;
    for(const item of answerList){
      item.slotValues = []
    }
    this.setState({
      answerList
    })
  }

  //删除一个词槽，则需要同步删除所有词槽答案中的该词槽选项
  //若该答案只有这一个词槽，则需要删除该答案
  removeSlotForOneOfAnswer = data => {
    const { answerList } = this.state;
    for(const item of answerList){
      item.slotValues = item.slotValues.filter(slot => slot.id != data.id)
    }
    console.log(answerList);
    const newAnswerList = answerList.filter(item => item.slotValues && item.slotValues.length > 0)
    this.setState({
      answerList:newAnswerList
    })
  }

  render(){
    const { answerSwitch,answerList } = this.state;
    const { slotData } = this.props;
    const addStyle = {
      position:'absolute',
      right:0,
      height:'32px',
      lineHight:'32px'
    }
    const answerHeader = item => {
      return (
        <div>
          {
            item.slotValues && item.slotValues.length > 0 ? 
            item.slotValues.map((slot,slotIndex) => {
              return (
                <span key={slotIndex} style={{marginRight:10}}>
                  <span style={{marginRight:8}}>&lt;{slot.slotName}&gt;=</span>
                  {
                    slot.values.map((slotValue,valueIndex) => {
                      return <Tag color='#F5F7FF' style={{ margin: '2px 8px 0 0', borderRadius: 12,color:'#3E5BFF',border:"1px solid #D6E0FF" }} key={valueIndex}>{slotValue}</Tag>
                    })
                  }
                </span>
              )
            }) : ''
          }
          {
            item.robotList && item.robotList.length > 0 ? 
            (
              <span style={{marginRight:10}}>
                <span style={{marginRight:8}}>&lt;{formatMessage({ id: 'moreAnswers.label.applicationName' })}&gt;=</span>
                {item.robotList.map((i, index) => {
                  return (
                    <Tag color='#FFE5CC' style={{ margin: '2px 8px 0 0', borderRadius: 12,color:'#663300' }} key={index}>{i.robotName}</Tag>
                  );
                })}
              </span>
            ) : null
          }
          {
            item.userTagIdList && item.userTagIdList.length > 0 ? 
            (
              <span>
                <span style={{marginRight:8}}>&lt;{formatMessage({ id: 'moreAnswers.label.userTag' })}&gt;=</span>
                {item.userTagIdList.map((tag, tagIndex) => {
                  return (
                    <Tag color='#DCE6FA' style={{ margin: '2px 8px 0 0', borderRadius: 12,color:'#000000' }} key={tagIndex}>{tag.tagName}</Tag>
                  );
                })}
              </span>
            ) : null
          }
        </div>
      )
    }
    const getExtra = (item,index) => UserSession.isSystemKnowledge() ? null : (
      <span>
        <img src={staticPath+'/appImg/edit.png'} className={styles.paneEdit} onClick={(e) => this.editAnswer(e,item,index)} />
        <Icon type="close-circle" className={styles.paneClose} onClick={(e) => this.removeAnswer(e,item,index)} />
      </span>
    )
    return(
      <div className={styles.moreAnswerStyle}>
        <div style={{position:'relative',margin:'20px 0'}}>
          {
            slotData && slotData.length > 0 ? <label style={{marginRight:20}}>{formatMessage({ id: 'moreAnswers.label.slotAnswer' })}</label> : UserSession.isAdmin() ? null :
             (
              <span>
                <label style={{marginRight:20}}>{formatMessage({ id: 'moreAnswers.label.personalizedAnswer' })}</label>
                <Radio.Group onChange={this.onChangeAnswerSwitch} value={answerSwitch} disabled={UserSession.isSystemKnowledge()}>
                  <Radio value={1}>{formatMessage({ id: 'moreAnswers.radio.enable' })}</Radio>
                  <Radio value={0}>{formatMessage({ id: 'moreAnswers.radio.disable' })}</Radio>
                </Radio.Group>
              </span>
            )
          }
          
          {
            ((answerSwitch && !UserSession.isAdmin()) || (slotData && slotData.length > 0)) && !UserSession.isSystemKnowledge() ? (
              <Button type="link" style={addStyle} onClick={() => this.openModal('add')}>{formatMessage({ id: 'moreAnswers.button.addAnswer' })}</Button>
            ) : ''
          }
        </div>
        {
          answerList && answerList.length > 0 && (answerSwitch == 1 || (slotData && slotData.length > 0))? 
          (
            <Collapse className="answerShow" bordered={false}>
              {
                answerList.map((item,index) => {
                  return (
                    <Collapse.Panel
                      key={index}
                      header={answerHeader(item)}
                      extra={getExtra(item,index)}
                    >
                      <ReferAnswerShow answer={item} hasBtn={false} />
                    </Collapse.Panel>
                  )
                })
              }
            </Collapse>
          ) : ''
        }
        

        <UpdateAnswerModal 
          onRef={ref => this.UpdateAnswerModal = ref} 
          answerSubmit={this.answerSubmit}
          slotData={slotData}
        />
      </div>
    )
  }
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(MoreAnswers);